import { useState, useRef, useEffect } from 'react';
import ResizeObserver from 'rc-resize-observer';
import { Table } from 'antd';


/**
 * 高度100%的Table组件，自动计算滚动大小
 */
const SpdTable = (props) => {
  const [contentHeight, setContentHeight] = useState(200);
  const [tableHeadHeight, setTableHeadHeight] = useState(0);// default 55px
  const [tablePageHeight, setTablePageHeight] = useState(0);// default 32px
  const containerRef = useRef(null);

  useEffect(() => {
    const tableHead = containerRef.current?.querySelector(".ant-table-thead");
    if (tableHead &&
      tableHead.clientHeight &&
      tableHead.clientHeight !== tableHeadHeight) {
      // 如果高度有变化重新设置高度
      setTableHeadHeight(tableHead.clientHeight);
    }

    const tablePage = containerRef.current?.querySelector(".ant-table-pagination");
    if (tablePage &&
      tablePage.clientHeight &&
      tablePage.clientHeight !== tablePageHeight) {
      // 如果高度有变化重新设置高度
      setTablePageHeight(tablePage.clientHeight);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [props.dataSource]);

  const onResize = ({ height }) => {
    setContentHeight(height);
  }

  let tableScrollY = contentHeight - tableHeadHeight;
  if (tablePageHeight > 0) {
    // page 上下有margin 16px
    tableScrollY = tableScrollY - tablePageHeight - 32;
  }
  if (props.bordered) {
    tableScrollY = tableScrollY - 1;
  }
  return (
    <ResizeObserver
      onResize={onResize}>
      <div
        style={{
          width: '100%',
          height: '100%',
        }}
        ref={containerRef}>
        <Table
          {...props}
          scroll={{
            y: tableScrollY,
          }}
        />
      </div>
    </ResizeObserver>)
};
export default SpdTable;